package com.yisu.expressway.location;


//import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import com.yisu.expressway.R;
import com.yisu.expressway.application.ExApplication;
import com.yisu.expressway.utils.HBLog;

/**
 * Created by Yue Zhen on 2016/1/24.
 */
public class LocationService implements BDLocationListener {
    private static final int GPS_SUCCESS_CODE = 61; // GPS定位结果，GPS定位成功
    private static final int NET_SUCCESS_CODE = 161; // 网络定位结果，网络定位定位成功
    private static final int OFFLINE_SUCCESS_CODE = 66; // 离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果
    private static final int OFFLINE_CACHE_SUCCESS_CODE = 65; // 定位缓存的结果
    private static final String tag = "LocationService";
    private static final String COOR_TYPE_GCJ = "gcj02";
    private static final String COOR_TYPE_GPS = "gps";
    private static final String COOR_TYPE_BD09 = "bd09";
    private static final String COOR_TYPE_BD09LL = "bd09ll";

    private static LocationService sInstance;
    private LocationClient mLocationClient;
    private LocationClientOption mOption;
    private LocationListener mResultListener;
    private LocationInfo mResultInfo; // it saves the latest location scanning result on storage

    public static LocationService getInstance() {
        if (sInstance == null) {
            sInstance = new LocationService();
        }
        return sInstance;
    }

    public void start() {
        mLocationClient = new LocationClient(ExApplication.getInstance().getApplicationContext());
        mLocationClient.setLocOption(mOption);
        mLocationClient.registerLocationListener(this);
        mLocationClient.start();
    }

    public void start(LocationListener listener) {
        mResultListener = listener;
        start();
    }

    public void stop() {
        //bug#1093,【Android】【系统】华为荣耀6手机使用猫空直播一会，手机发烫
        //有时候start失败了，就没有stop了，导致定位一直在。
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(this);
            mLocationClient.stop();
            mResultListener = null;
            mLocationClient = null;
        }
    }

    public LocationInfo getLocationResult() {
        return mResultInfo;
    }

    public void clearLastLocationInfo(){
        mResultInfo = null;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        int resultCode = location.getLocType();
        HBLog.d(tag, "onReceiveLocation resultCode = " + resultCode);

        if (GPS_SUCCESS_CODE == resultCode || NET_SUCCESS_CODE == resultCode || OFFLINE_SUCCESS_CODE == resultCode
                || OFFLINE_CACHE_SUCCESS_CODE == resultCode) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            String address = location.getAddrStr();

            mResultInfo = new LocationInfo(address, latitude, longitude);
            mResultInfo.setProvince(location.getProvince());
            mResultInfo.setCity(location.getCity());
            mResultInfo.setDistrict(location.getDistrict());
            mResultInfo.setStreet(location.getStreet());


            if (mResultListener != null) {
                mResultListener.onSuccess(mResultInfo);
            }

            HBLog.d(tag, "onReceiveLocation success latitude = " + latitude + " , longitude = " +
                    "" + longitude + " , address = " + address);
        } else {
            HBLog.d(tag, "onReceiveLocation error");
            if (mResultListener != null) {
                mResultListener.onFailure(resultCode, getErrorMessage(resultCode));
            }
        }

        stop();
    }

    private LocationService() {
        initOption();
    }

    private void initOption() {
        if (mOption == null) {
            mOption = new LocationClientOption();
        }
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        mOption.setCoorType(COOR_TYPE_BD09LL);//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        mOption.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        mOption.setIsNeedLocationDescribe(true);//可选，设置是否需要地址描述

        //bug#1093,【Android】【系统】华为荣耀6手机使用猫空直播一会，手机发烫
        //mocon对于定位只是简单应用，不需要bd的定位服务一直在，卸磨杀驴，免得驴吃太多，挺好
        mOption.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        mOption.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        mOption.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集

    }


    private String getErrorMessage(int errorCode) {
        int resId = 0;
        String msg = null;
        switch (errorCode) {
            case BDLocation.TypeServerError:
                resId = R.string.location_server_error;
                break;
            case BDLocation.TypeNetWorkException:
                resId = R.string.location_network_error;
                break;
            case BDLocation.TypeCriteriaException:
                resId = R.string.location_criteria_error;
                break;
            default:
                resId = R.string.location_unknown_error;
                break;
        }

        msg = ExApplication.getInstance().getResources().getString(resId);
        return msg;
    }
}
